﻿using IM.Easy.Core.Enums;
using IM.Easy.Core.Log;
using IM.Easy.Core.Result;
using IM.Easy.Core.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace IM.Easy.Core.Middleware
{
    public class ImExceptionHandlingMiddleware : IMiddleware
    {
        private readonly IExceptionLogger _logger;

        public ImExceptionHandlingMiddleware(IExceptionLogger logger)
        {
            _logger = logger;
        }


        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {

                // 处理异常并返回响应
                await HandleExceptionAsync(context, ex);
            }

        }

        private async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            ApiResult result;
            try
            {
                await _logger.Log(context, exception);
                var type = exception.GetType();
                var statusCode = ExceptionUtils.GetStatusCode(type);
                switch (statusCode)
                {
                    case ResultCode.Unauthorized:
                        result = ApiResult.Failure(exception.Message, statusCode);
                        break;
                    case ResultCode.InternalServerError:
                        result = ApiResult.Failure("系统异常", statusCode);
                        break;
                    case ResultCode.BusinessLogicError:
                        result = ApiResult.Failure(exception.Message, statusCode);
                        break;
                    default:
                        result = ApiResult.Failure("未知错误", statusCode);
                        break;
                }
            }
            catch (Exception ex)
            {
                result = ApiResult.Failure("未知错误");
            }
            // 记录异常日志

            context.Response.ContentType = "application/json";
            context.Response.StatusCode = 200;
            var options = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,  // 设置为驼峰命名
                WriteIndented = true  // 如果需要格式化输出，可以设置为 true
            };
            var jsonString = JsonSerializer.Serialize(result, options);

            await context.Response.WriteAsync(jsonString);
        }
    }


}
